public class Choicepoint {
    Stack<Variable> bindings;
    Stack<Conjunct> query;
    boolean dead;
    
    public Choicepoint() {}
    
    public Choicepoint(Stack<Conjunct> continuation, int cutIndex, Term... term) {
        bindings = null;
        query = continuation;
        
        for(int i = term.length-1; i >= 0; i--)
            query = new Stack<Conjunct>(new Conjunct(term[i],cutIndex),query);
        
        dead = false;
    }
    
    public void undoBindings() {
        while(bindings != null) {
            bindings.head.unbind();
            bindings = bindings.tail;
        }
    }
    
    public void addQuerents(int cutIndex, Term... querents) {
        for(int i = querents.length-1; i >= 0; i--) {
            query = new Stack<Conjunct>(new Conjunct(querents[i],cutIndex),query);
        }
    }
    
    public void addBindings(Stack<Variable> newBindings) {
        // change this to an efficient version using mutation? (less allocation)
        while(newBindings != null) {
            bindings = new Stack<Variable>(newBindings.head,bindings);
            newBindings = newBindings.tail;
        }
    }
    
    public Choicepoint incrementQueryHeadChoice() {
        Choicepoint c = new Choicepoint();
        c.bindings = bindings;
        c.query = new Stack<Conjunct>(query.head.increment(),query.tail);
        c.dead = dead;
        return c;
    }
}

